# 无名之辈电影下载脚本
import m3u8
from concurrent.futures import ThreadPoolExecutor
import requests
pool_size = 20
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
}


def download(url):
    while True:
        try:
            name = url.split("/")[-1].replace("ts", "mp4")
            path = "movie/{}".format(name)
            res = requests.get(url,verify=False,headers=headers,timeout=10)
            if not str(res.status_code).startswith("4"):
                return (path,res.content)
            else :
                raise  Exception("404 not found:{}".format(url))
        except Exception as e:
            print("{}:{}".format(url,repr(e)))


def download_video_m3u8(url,name):
    fielname = "{}.mp4".format(name.replace("/",""))
    pool = ThreadPoolExecutor(max_workers=pool_size)
    ts_req = requests.get(url,headers=headers,verify=False)
    if str(ts_req.status_code).startswith("4"):
        return str(ts_req)
    m3u8_obj = m3u8.loads(ts_req.text,url)
    if len(m3u8_obj.playlists)!=0: # mu83 重定向
        url = m3u8_obj.playlists[0].absolute_uri
    ts_req = requests.get(url, headers=headers, verify=False).text
    m3u8_obj = m3u8.loads(ts_req, url)
    ts_list = [i.absolute_uri for i in m3u8_obj.segments]
    sum = len(ts_list)
    count = 0
    for path,i in pool.map(download,ts_list):
        f = open(fielname, "ab")
        f.write(i)
        count+=1
        f.close()
        print("文件大小{}，以下载{}".format(sum,count))
    return ""







